//为每一行代码添加注释
const express = require('express');
const cors = require('cors');
const joi = require("joi");
const bodyParser = require('body-parser');
const multiparty = require('connect-multiparty');
const app = express();
app.use(cors())
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
//app.use(multiparty());

// 公开静态文件夹 public/upload
app.use('/img/', express.static('./public/upload/'))

// 全局中间件
app.use((req, res, next) => {
    // 定义一个输出的函数
    res.output = function (err, status = 1, data) {
        res.send({
            status,
            message: err instanceof Error ? err.message : err,
            data,
        });
    };
    next();
});


// 在路由之前配置解析token的中间件
const { expressjwt: jwt } = require("express-jwt");
// 解析token需要token的密钥
const config = require("./config");
// 定义中间件，需要哪个密钥解析，.unless指定哪些接口不需要进行token身份认证
app.use(
    jwt({ secret: config.jwtSecretKey, algorithms: ["HS256"] }).unless({
        path: [/^\/api/,/^\/img\//],
        message: "请先登录",
    })
);

// 导入router
const loginRouter = require('./router/login')
app.use("/api", loginRouter)
const getSalespersonRouter = require('./router/getSalesperson')
app.use(getSalespersonRouter)
const addSalespersonRouter = require('./router/addSalesperson')
app.use(addSalespersonRouter)
const updateSalespersonRouter = require('./router/updateSalesperson')
app.use(updateSalespersonRouter)
const removeSalespersonRouter = require('./router/removeSalesperson')
app.use(removeSalespersonRouter)
const querySalespersonRouter = require('./router/querySalesperson')
app.use("/api",querySalespersonRouter)
const querySalespersonByUidRouter = require('./router/querySalespersonByUid')
app.use("/api",querySalespersonByUidRouter)
// 企业信息
const getEnterpriseRouter = require('./router/getEnterprises')
app.use(getEnterpriseRouter)


// 添加企业
const addEnterpriseRouter = require('./router/addEnterprise')
app.use(addEnterpriseRouter)

// 删除企业
const removeEnterpriseRouter = require('./router/removeEnterprise')
app.use(removeEnterpriseRouter)

// 修改企业
const updateEnterpriseRouter = require('./router/updateEnterprise')
app.use(updateEnterpriseRouter)

//根据id查询企业
const queryEnterpriseByIdRouter = require('./router/queryEnterpriseByid')
app.use("/api",queryEnterpriseByIdRouter)

const getEnterpriseRouterAll = require('./router/getEnterprises')
app.use("/api",getEnterpriseRouterAll)

// 上传图片
const uploadRouter = require('./router/upload')
app.use(uploadRouter)

// 修改系统密码
const updateSystempasswordRouter = require('./router/updateSystempassword')
app.use(updateSystempasswordRouter)

// 在所有路由下面调用错误级别的中间件
app.use((err, req, res, next) => {
    if (err.name === "UnauthorizedError") {
        return res.status(401).send({ message: "请先登录" });
    }
    // 验证失败导致的错误
    if (err instanceof joi.ValidationError) return res.output(err);

    // 未知的错误
    res.output(err);
    next();
});

// 启动
app.listen(4000, () => {
    console.log('express server running at http://127.0.0.1:' + 4000);
})

